<script setup lang="ts">
import { computed, ref, onMounted, reactive } from 'vue';
import Button from '../components/Button.vue';
import axios from  'axios';
import {ElMessage } from 'element-plus'




/** ========================= 转换type --在后端完成了 ========================= **/
/**
 * 学生类型
 * 0代表择校生
 * 1代表免学费生
 * 2代表正常考入学生
 */

/** ========================= 静态变量 ========================= **/
//表头
    interface TableHeader {
      columnLabel: string;
      columnName: string;
}
// 使用 ref 声明数据列表，以便进行筛选操作
// const dataList = ref([...originalDataList]);


/** ========================= 新增表单数据 ========================= **/
const dialogFormVisible = ref(false)
const formLabelWidth = '140px'

const form = reactive({
  name: '',
  age: '',
  gender: '',
  school: '',
  qualification: ''
})
const resetForm = () => {
  form.name = '';
  form.age = '';
  form.gender = '';
  form.school = '';
  form.qualification = '';
}
 const submitForm = async () => {
  try {
    const response = await axios.post('http://localhost:3000/api/add',form);
    console.log(response.data.message);
    //成功消息
    ElMessage({
      message: '学生信息添加成功！',
      type: 'success',
      duration: 2000 // 提示持续时间，单位为毫秒
    });
    dialogFormVisible.value= false;
    fetchData();
    resetForm();
  } catch (error) {
    ElMessage({
      message: '添加失败!',
      type: 'error',
      duration: 2900
    })
    console.error('提交表单错误:',error);
  }
 }

/** ========================= 筛选条件 ========================= **/
const selectedAge = ref('');
const selectedGender = ref('');
const selectedSchool = ref('');
const selectedQualification = ref('');
const inputName = ref('');

/** ========================= 筛选后端数据  ========================= **/

const FilterBackendData = () => {
  //所有条件为空的时候
  if (!inputName.value && !selectedAge.value && !selectedGender.value && !selectedSchool.value && !selectedQualification.value) {
    filteredTables.value = backend_tables.value;  // 恢复到原始数据
    return;
  }
  filteredTables.value = backend_tables.value.filter((row) => {
    return (
        (!inputName.value || row.name.includes(inputName.value)) && // 确保模糊搜索生效
        (!selectedAge.value || row.age === Number(selectedAge.value)) &&
        (!selectedGender.value || row.gender === selectedGender.value) &&
        (!selectedSchool.value || row.school === selectedSchool.value) &&
        (!selectedQualification.value || row.qualification === selectedQualification.value)
    );
  });
}
/** ---------- 清除选中 ---------- **/
const clearAll = () => {
  filteredTables.value  = backend_tables.value;
}
/** ========================= 删除函数  ========================= **/
const selectedRows = ref([]); // 存储选中的行
/** ---------- 留下选中的行的内容 在selectdRows里面 ---------- **/
const handleSelectionChange = (val: any) => {
  selectedRows.value = val;
  console.log(selectedRows.value);
};
/** ---------- 发送请求 ---------- **/
const deleteSelectedRows = async () => {
  if (selectedRows.value.length === 0) {
    // 正确使用 ElMessage 显示警告
    ElMessage({
      message: '请先选择要删除的行',
      type: 'warning',
      duration: 2000,
    });
    return;
  }
  // 获取选中行的 id
  const ids = selectedRows.value.map((row: any) => row.id);
  // 发送请求
  try {
    await axios.delete('http://localhost:3000/api/delete', {
      data: { ids },
      headers: { 'Content-Type': 'application/json' } // 明确指定请求头类型
    });
    // 显示删除成功的消息
    ElMessage({
      message: '删除成功',
      type: 'success',
      duration: 2000,
    });
    // 删除成功后重新获取数据
    fetchData();
  } catch (error) {
    // 显示删除失败的消息
    ElMessage({
      message: '删除失败',
      type: 'error',
      duration: 2000
    });
    console.error('删除失败', error);
  }
};
/** ========================= 修改功能  ========================= **/
//弹出框是否可以见
const editDialogVisible = ref(false);
//存储编辑的数据
const editData = ref({});
const handleChange = (row :any) => {
  console.log('选中的行数据:', row);
  editData.value= {...row};
  editDialogVisible.value = true;
}
/** ---------- 提交修改 ---------- **/
const submitEdit = () => {
  updateData();
}
/** ========================= 根据id查找信息  ========================= **/
// const findById = (id: number) => {
//   axios.get('http://localhost:3000/api/findById',{
//     params: {id},
//   }).then(res => {
//     editData.value = res.data;
//   })
// }
/** ========================= 更新函数  ========================= **/
const updateData = async () => {
  try {
    const response = await axios.put('http://localhost:3000/api/update', editData.value);
    console.log(response.data.message);
    //成功消息
    ElMessage({
      message: '学生信息修改成功！',
      type: 'success',
      duration: 2000 // 提示持续时间，单位为毫秒
    });
    editDialogVisible.value= false;
    fetchData();
  } catch (error) {
    ElMessage({
      message: '修改失败!',
      type: 'error',
      duration: 2900
    })
    console.error('提交表单错误:',error);
  }
}

/** ========================= 分页相关 ========================= **/


/** =========================根据学历返回标签类型的方法 ========================= **/


/** ========================= axios获取后端数据 ========================= **/
const fetchData = () => {
  axios.get('http://localhost:3000/api/data-list')
      .then(res =>{
        backend_tables.value = res.data;
        filteredTables.value = [...backend_tables.value];
        console.log(res.data);
      })
  //表头
  axios.get('http://localhost:3000/api/table-header')
      .then(res => {
        backend_header.value= res.data;
      })
}
//计算唯一的年龄下拉选项
const uniqueAges = computed(() => {
  const ages = backend_tables.value.map(item => item.age); // 提取所有年龄
  const uniqueAgesSet = [...new Set(ages)]; // 去重
  return uniqueAgesSet.sort((a, b) => a - b); // 数值升序排序
});
//计算唯一的学历下拉选项
const uniqueQualifications = computed(() => {
  const qualifications = backend_tables.value.map(item => item.qualification);
  return [...new Set(qualifications)];
})

const backend_tables = ref([]);
const filteredTables = ref([]); // 用于存储筛选后的数据
const backend_header = ref<TableHeader[]>([]);
onMounted(() => {
  fetchData();
});
</script>

<template>
  <div class="table">

<!--分割线-->
    <el-divider></el-divider>
    <h1>数据库表格</h1>
<!--    查询条件-->
    <div>
<!--     姓名-->
      <el-form-item label="姓名" prop="name">
        <el-input v-model="inputName" placeholder="输入姓名进行模糊查询" style="margin-right: 10px; width: 200px;" @input="FilterBackendData">
        </el-input>
      </el-form-item>
      <el-form-item label="年龄" prop="age">
        <el-select v-model="selectedAge" clearable placeholder="选择年龄"  @change="FilterBackendData" style="margin-right: 10px; width: 120px;">
<!--          <el-option label="18" value="18" />-->
<!--          <el-option label="19" value="19" />-->
          <el-option v-for="age in uniqueAges" :key="age" :label="age" :value="age"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="性别" prop='sex'>
      <el-select v-model="selectedGender" clearable placeholder="选择性别" @change="FilterBackendData" style="margin-right: 10px; width: 120px;">
        <el-option label="男" value="男" />
        <el-option label="女" value="女" />
      </el-select>
      </el-form-item>
      <el-form-item label="学校" prop="school">
        <el-input v-model="selectedSchool" clearable @change="FilterBackendData" placeholder="请输入学校" style="margin-right: 10px; width: 140px;">
        </el-input>
      </el-form-item>
      <el-form-item label="学历" prop="qualification">
        <el-select v-model="selectedQualification" @change="FilterBackendData" clearable placeholder="选择学历" style="margin-right: 10px; width: 120px;">
<!--          <el-option label="博士" value="博士" />-->
<!--          <el-option label="研究生" value="研究生" />-->
<!--          <el-option label="本科" value="本科" />-->
<!--          <el-option label="初中" value="初中" />-->
          <el-option v-for="qu in uniqueQualifications" :value="qu" :label="qu"></el-option>
        </el-select>
      </el-form-item>
    </div>
    <el-divider></el-divider>
<!--    按钮-->
    <div>
      <!--      新增按钮-->
      <el-button type="primary" plain @click="dialogFormVisible = true">
        新增
      </el-button>
<!--      删除按钮-->
      <el-button type="danger" plain @click="deleteSelectedRows">
        删除
      </el-button>
<!--      搜索按钮-->
      <el-button type="primary" plain @click="fetchData">
        搜索
      </el-button>
<!--      清空按钮-->
      <el-button type="info" plain @click="clearAll">
        清空已选择
      </el-button>
    </div>
<!--    分割线-->
    <el-divider></el-divider>
    <el-table :data="filteredTables" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" />
      <el-table-column
          v-for="(item, index) in backend_header"
          :key="index"
          :label="item.columnLabel"
          :prop="item.columnName"
      >
      </el-table-column>
<!--      增加修改按钮-->
      <el-table-column fixed="right" label="操作" min-width="120">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="handleChange(scope.row)">
            修改
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-divider></el-divider>
    <h1>打开表单</h1>

<!--    打开表单内容-->
    <div>
      <el-divider></el-divider>
      <el-dialog v-model="dialogFormVisible" title="填写新增内容" width="500">
        <el-form :model="form">
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="form.name" autocomplete="off"placeholder="请输入姓名" />
          </el-form-item>
          <!--        年龄-->
          <el-form-item label="年龄" :label-width="formLabelWidth">
            <el-input v-model="form.age" autocomplete="off" placeholder="请输入年龄" />
          </el-form-item>
          <!--选择性别-->
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-radio-group v-model="form.gender">
              <el-radio label="男" />
              <el-radio label="女" />
            </el-radio-group>
          </el-form-item>
          <!--填写学校-->
          <el-form-item label="学校" :label-width="formLabelWidth">
            <el-input v-model="form.school" autocomplete="off" placeholder="请输入学校" />
          </el-form-item>
          <el-form-item label="学历" :label-width="formLabelWidth">
            <el-select v-model="form.qualification" placeholder="请选择学历">
              <el-option label="专科" value="专科" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

<!--    修改表单内容-->
    <div>
      <el-divider></el-divider>
      <el-dialog v-model="editDialogVisible" title="修改内容" width="500">
        <el-form :model="editData">
          <el-form-item label="姓名" :label-width="formLabelWidth">
            <el-input v-model="editData.name" autocomplete="off"placeholder="请输入姓名" />
          </el-form-item>
          <!--        年龄-->
          <el-form-item label="年龄" :label-width="formLabelWidth">
            <el-input v-model="editData.age" autocomplete="off" placeholder="请输入年龄" />
          </el-form-item>
          <!--选择性别-->
          <el-form-item label="性别" :label-width="formLabelWidth">
            <el-radio-group v-model="editData.gender">
              <el-radio label="男" />
              <el-radio label="女" />
            </el-radio-group>
          </el-form-item>
          <!--填写学校-->
          <el-form-item label="学校" :label-width="formLabelWidth">
            <el-input v-model="editData.school" autocomplete="off" placeholder="请输入学校" />
          </el-form-item>
          <el-form-item label="学历" :label-width="formLabelWidth">
            <el-select v-model="editData.qualification" placeholder="请选择学历">
              <el-option label="专科" value="专科" />
              <el-option label="本科" value="本科" />
              <el-option label="硕士" value="硕士" />
              <el-option label="博士" value="博士" />
            </el-select>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="editDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitEdit">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>

  </div>
</template>

<style scoped>
/* 这里可以加入你的样式 */
</style>
